package com.cmic.rcs.emoji.service.impl;

import com.cmic.rcs.emoji.common.UserContext;
import com.cmic.rcs.emoji.entity.dto.PageRequest;
import com.cmic.rcs.emoji.entity.pojo.TEnterprise;
import com.cmic.rcs.emoji.entity.pojo.TEnterpriseMember;
import com.cmic.rcs.emoji.entity.vo.EnterpriseVo;
import com.cmic.rcs.emoji.entity.vo.PageResult;
import com.cmic.rcs.emoji.mapper.EnterpriseMapper;
import com.cmic.rcs.emoji.mapper.TEnterpriseMemberMapper;
import com.cmic.rcs.emoji.service.EnterpriseService;
import com.cmic.rcs.emoji.util.AddressBookApiUtil;
import com.cmic.rcs.emoji.util.SessionManageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 孙高明
 * @since 2025-10-09
 */
@Service
@Slf4j
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    private SessionManageUtil sessionManageUtil;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private AddressBookApiUtil addressBookApiUtil;

    @Autowired
    private TEnterpriseMemberMapper tEnterpriseMemberMapper;

    @Autowired
    private RestTemplate restTemplate;

//    @Value("${address-book.appKey}")
//    String appKey;
//
//    @Value("${address-book.appSecret}")
//    String appSecret;

    @Override
    public PageResult<EnterpriseVo> list(PageRequest pageRequest) {
        // 设置分页参数
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        // 如果有排序字段，设置排序
        if (StringUtils.isNotBlank(pageRequest.getSortField()) && StringUtils.isNotBlank(pageRequest.getSortOrder())) {
            PageHelper.orderBy(pageRequest.getSortField() + " " + pageRequest.getSortOrder());
        }

        // 查询企业列表
        List<TEnterprise> enterprises = enterpriseMapper.EnterpriseselectList();
        log.info("查询企业列表成功{}条", enterprises.size());

        // 转换为PageInfo获取总数
        PageInfo<TEnterprise> pageInfo = new PageInfo<>(enterprises);

        // 准备返回结果
        PageResult<EnterpriseVo> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());

        List<EnterpriseVo> enterpriseVos = new ArrayList<>();

        // 如果有数据，进行处理
        if (!enterprises.isEmpty()) {
            // 提取企业编码列表（假设orgId在addressBookApiUtil中对应enterpriseCode）
            List<Long> orgIds = new ArrayList<>();
            for (int i = 0; i < enterprises.size(); i++) {
                String enterpriseCode = enterprises.get(i).getEnterpriseCode();
                //转换为Long类型
                Long code = Long.valueOf(enterpriseCode);
                orgIds.add(code);
            }
            log.info("企业编码列表：{}", orgIds);

            // 批量获取企业名称
            Map<Long, String> enterpriseNameMap = addressBookApiUtil.batchGetEnterpriseNames(orgIds);

            // 组装EnterpriseVo
            for (TEnterprise enterprise : enterprises) {
                EnterpriseVo vo = new EnterpriseVo();
                vo.setId(enterprise.getId());
                vo.setEnterpriseCode(enterprise.getEnterpriseCode());

                // 从通讯录获取企业名称
                try {
                    Long orgId = Long.valueOf(enterprise.getEnterpriseCode());
                    String enterpriseName = enterpriseNameMap.get(orgId);
                    if (StringUtils.isNotBlank(enterpriseName)) {
                        vo.setEnterpriseName(enterpriseName);
                    } else {
                        // 如果获取不到，设置为默认值
                        vo.setEnterpriseName("XXX企业");
                    }
                } catch (NumberFormatException e) {
                    vo.setEnterpriseName("XXX企业");
                    log.error("获取企业名称失败: {}", enterprise.getEnterpriseCode(), e);
                }

                vo.setEnterpriseStatus(enterprise.getEnterpriseStatus());
                vo.setCreateTime(enterprise.getCreateTime().toString());

                // 对创建人手机号进行脱敏处理
                String createBy = enterprise.getCreateBy();
                if (createBy != null && createBy.length() == 11) {
                    vo.setCreateBy(createBy.substring(0, 3) + "****" + createBy.substring(7));
                } else {
                    vo.setCreateBy(createBy);
                }

                enterpriseVos.add(vo);
            }
        }

        pageResult.setList(enterpriseVos);
        return pageResult;
    }

    @Override
    public void addEnterprise(EnterpriseVo enterpriseVo) {
        // 1. 创建TEnterprise对象
        TEnterprise tEnterprise = new TEnterprise();
        // 2. 获取企业名称，根据企业名称在通讯录查找企业信息
        String enterpriseName = enterpriseVo.getEnterpriseName();
        if (enterpriseName != null && !enterpriseName.trim().isEmpty()) {
            // 3. 根据企业名称在通讯录中查询企业信息
            List<Map<String, Object>> maps = addressBookApiUtil.queryEnterpriseByOrgName(enterpriseName);
            if (maps != null && !maps.isEmpty()) {
                Map<String, Object> map = maps.get(0);
                // 4.保存企业信息到数据库
                tEnterprise.setEnterpriseCode(map.get("enterpriseCode").toString());
                tEnterprise.setEnterpriseStatus(1); // 启用
                tEnterprise.setCreateTime(LocalDateTime.now());
                tEnterprise.setUpdateTime(LocalDateTime.now());
                tEnterprise.setCreateBy(UserContext.getUserDto().getUsername()); // 获取当前用户名
                enterpriseMapper.insert(tEnterprise);
                log.info("新增企业信息成功");
            }else {
                log.error("企业名称[{}]在通讯录中未找到", enterpriseName);
                throw new RuntimeException("企业名称[{}]在通讯录中未找到");
            }
        } else if (StringUtils.isEmpty(enterpriseName)) {
            log.error("企业名称不能为空");
            throw new RuntimeException("企业名称不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEnterprise(String enterpriseCode) {
        try {
            // 1. 参数校验
            if (StringUtils.isBlank(enterpriseCode)) {
                log.error("企业编码不能为空");
                throw new RuntimeException("企业编码不能为空");
            }

            // 2. 验证企业是否存在
            TEnterprise existingEnterprise = enterpriseMapper.selectByEnterpriseCode(enterpriseCode);
            if (existingEnterprise == null) {
                log.error("企业不存在，企业编码: {}", enterpriseCode);
                throw new RuntimeException("企业不存在");
            }

            // 3. 获取企业所有成员，用于强制下线
            List<TEnterpriseMember> members = tEnterpriseMemberMapper.selectListAll(enterpriseCode);

            if (members != null && !members.isEmpty()) {
                log.info("企业[{}]所有成员：{}", enterpriseCode, members.size());
                // 4. 对每个成员调用强制下线接口
                for (TEnterpriseMember member : members) {
                    String phoneNumber = member.getMemberAccount();
                    if (phoneNumber != null && phoneNumber.length() == 11) {
                        try {
                            boolean logoutResult = sessionManageUtil.forceLogoutByPhone(phoneNumber);
                            log.info("强制下线用户[{}]，结果：{}", "******" + phoneNumber.substring(6), logoutResult);
                        } catch (Exception e) {
                            log.warn("强制下线用户[{}]失败: {}", "******" + phoneNumber.substring(6), e.getMessage());
                            // 继续处理其他用户，不中断删除流程
                        }
                    }
                }
            }

            // 5. 删除企业成员信息
            int memberDeleteCount = tEnterpriseMemberMapper.deleteByEnterpriseCode(enterpriseCode);
            log.info("删除企业成员信息成功，删除记录数: {}", memberDeleteCount);

            // 6. 删除企业信息
            int enterpriseDeleteCount = enterpriseMapper.deleteEnterpriseCode(enterpriseCode);
            if (enterpriseDeleteCount > 0) {
                log.info("删除企业信息成功，企业编码: {}", enterpriseCode);
            } else {
                log.warn("未删除任何企业信息，企业编码: {}", enterpriseCode);
            }

        } catch (Exception e) {
            log.error("删除企业失败，企业编码: {}", enterpriseCode, e);
            throw new RuntimeException("删除企业失败: " + e.getMessage());
        }
    }
}
